package com.example.asus.shixun2.control;

import android.content.Context;
import android.graphics.Canvas;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.example.asus.shixun2.R;
import com.example.asus.shixun2.Tool;
import com.example.asus.shixun2.model.BoxsModel;
import com.example.asus.shixun2.model.MapModel;
import com.example.asus.shixun2.model.ScoreModel;

/**
 * Created by ASUS on 2019/1/2.
 */

public class GameControl {

    public Handler handler;
    //方块模型
    BoxsModel boxsModel;
    //地图模型
    MapModel mapModel;
    //分数栏模型
    ScoreModel scoreModel;
    public Thread downThread;//下落线程

    public boolean isPause;//暂停状态
    public boolean isOver;//游戏结束状态
    public boolean is_left_right = false;//左右移动状态
    public boolean isMusic = true;//背景音乐
    public boolean isSound = true;//背景音效

    Context context;//连接上下文

    private MediaPlayer mediaPlayer_delete;//声明背景音乐播放器
    private MediaPlayer mediaPlayer_bg;
    private MediaPlayer mediaPlayer_over;

    int boxSize;//方块大小

    public GameControl(Handler handler,Context context){
        this.handler = handler;
        this.context = context;
        initData(context);
//        initMediaPlayer(context);
        boxsModel.newBoxsNext();
    }

    public GameControl() {
    }

    /**初始化数据*/
    private void initData(Context context) {
        //获得屏幕宽度
        int height = getScreenHeight(context);
        //设置游戏区域宽度=屏幕宽度*（2/3），高度=宽度*2
        Tool.xWidth = height / 3 * 2;
        Tool.xHeight = height;
        //设置分数栏区域宽度=屏幕宽度*（1/3），高度=宽度*3
        Tool.sWidth = height / 4;
        Tool.sHeight = Tool.sWidth + 100 ;
        //初始化方块大小
        boxSize = Tool.xWidth / Tool.MAPX;
        //初始化地图
        mapModel = new MapModel(boxSize,Tool.xWidth,Tool.xHeight,context);
        //实例化方块
        boxsModel = new BoxsModel(boxSize);
        //实例化分数栏
        scoreModel = new ScoreModel(boxSize);
        

    }

    /**获得屏幕宽度*/
    public static int getScreenHeight(Context context){
        WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**开始游戏*/
    private void startGame() {

        Tool.score = 0;
        isOver = false;
        isPause = false;
        Message msg = new Message();
        msg.obj = "Pause";
        handler.sendMessage(msg);
        mediaPlayer_bg.start();

        if(downThread == null){
            downThread = new Thread(){
                @Override
                public void run() {
                    super.run();
                    while(true){
                        try {
                            sleep(Tool.speed);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //判断游戏是否处于结束状态
                        //判断是否处于暂停状态
                        if(isPause || isOver) {
                            mediaPlayer_bg.pause();
                            continue;//跳过后面代码，执行循环
                        }else if(isMusic){
                            mediaPlayer_bg.start();
                        }
//                        mapModel.cleanLine(isSound,mediaPlayer_delete);
                        //执行一次下落
                        moveBottom();

                       //通知主线程刷新view
                        Message msg = new Message();
                        msg.obj = "invalidate";
                        handler.sendMessage(msg);
                    }
                }
            };
            downThread.start();//启动线程
        }
        //调用清除地图方法
        mapModel.clearMaps();
        //生成的方块
        boxsModel.newBoxs();
    }

    /**下落*/
    public boolean moveBottom(){
        //1、移动成功，不做处理
        if(boxsModel.move(0,1,mapModel)) {
            return true;
        }
        //2、移动失败堆积处理
        for(int i = 0;i < boxsModel.boxs.length;i ++){
            mapModel.maps[boxsModel.boxs[i].x][boxsModel.boxs[i].y] = true;
        }
        //3、消行处理
        mapModel.cleanLine(isSound,mediaPlayer_delete);
        //4、生成新的方块
        boxsModel.newBoxs();
        //5、判断游戏结束
        isOver = checkOver();
        if(isOver) mediaPlayer_over.start();
        return false;

    }



    /**游戏结束判断*/
    public boolean checkOver(){
        for(int i = 0;i <boxsModel.boxs.length;i ++){
            if(mapModel.maps[boxsModel.boxs[i].x][boxsModel.boxs[i].y]){
                return true;
            }
        }
        return false;
    }

    /**控制绘制*/
    public void draw_game(Canvas canvas) {
        mapModel.drawBG(canvas);
        //调用绘制地图的方法
        mapModel.drawMaps(canvas);
        //调用绘制方块的方法
        boxsModel.drawBoxs(canvas);
        //调用绘制地图辅助线方法
        mapModel.drawLine(canvas);

        //调用暂停、结束状态显示方法
        mapModel.drawPause(canvas,isOver,isPause);
    }

    /**设置暂停状态*/
    private void setPause() {
        if(isPause){
            isPause = false;
            Message msg = new Message();
            msg.obj = "Pause";
            handler.sendMessage(msg);
        }
        else{
            isPause = true;
            Message msg = new Message();
            msg.obj = "Continue";
            handler.sendMessage(msg);
        }
    }

    /**按钮监听*/
    public void onClick(int id) {
        if(boxsModel.boxs == null){
            if(id == R.id.bt_start){
                startGame();
            }
            return;
        }
        switch (id){
            //左按钮监听
            case R.id.bt_left :
                if(isPause) return;
                boxsModel.move(-1,0,mapModel);
                is_left_right = true;
                break;
            //右按钮监听
            case R.id.bt_right :
                if(isPause) return;
                boxsModel.move(1,0,mapModel);
                is_left_right = true;
                break;
            //上按钮监听
            case R.id.bt_up :
                if(isPause) return;
                boxsModel.rotate(mapModel);
                break;
            //下按钮监听，执行快速下落
            case R.id.bt_down :
                if(isPause) return;
                while(true) {
                    //如果下落失败，结束循环
                    if(!moveBottom()){
                        break;
                    }
                }
                break;
            //开始按钮监听
            case R.id.bt_start :
                startGame();
                break;
            //暂停按钮监听
            case R.id.bt_pause :
                setPause();
                break;
            case R.id.bt_music :
                setMusic();
                break;
            case R.id.bt_sound :
                setSound();
                break;
        }
    }

    /**背景音效*/
    private void setSound() {
        if(isSound){
            isSound = false;
            Message msg = new Message();
            msg.obj = "No_Sound";
            handler.sendMessage(msg);
        }else{
            isSound = true;
            Message msg = new Message();
            msg.obj = "Yes_Sound";
            handler.sendMessage(msg);
        }
    }

    /**背景音乐*/
    private void setMusic() {
        if(isMusic){
            isMusic = false;
            Message msg = new Message();
            msg.obj = "No_Music";
            handler.sendMessage(msg);
            mediaPlayer_bg.pause();
        }else{
            isMusic = true;
            Message msg = new Message();
            msg.obj = "Yes_Music";
            handler.sendMessage(msg);
            mediaPlayer_bg.start();
        }
    }

    /**初始化播放器*/
    public void initMediaPlayer(Context context) {
        if(mediaPlayer_delete==null) {
            mediaPlayer_delete = MediaPlayer.create(context, R.raw.delete);

        }
        if(mediaPlayer_bg == null){
            mediaPlayer_bg = MediaPlayer.create(context,R.raw.bg);
            mediaPlayer_bg.setLooping(true);
        }
        if(mediaPlayer_over == null){
            mediaPlayer_over = MediaPlayer.create(context,R.raw.defeat);
            mediaPlayer_over.setLooping(false);
        }
    }

    public void draw_score(Canvas canvas) {
        //调用分数栏中下一个方块辅助线方法
        scoreModel.drawNext_boxs(canvas);
        scoreModel.drawNextLine(canvas);
        boxsModel.drawNext(canvas);
        scoreModel.drawScore(canvas);
    }

    public void pauseMusic() {
        mediaPlayer_bg.stop();
    }


}
